((window, undefined) => {
  const ps = "absolute";
  class Snake {
    constructor(params) {
      params = params instanceof Object ? params : {};
      // 设置蛇节
      this.width = params.width || 20;
      this.height = params.height || 20;
      // 设置蛇身
      this.body = [
        { x: 3, y: 2, color: 'red' },
        { x: 2, y: 2, color: 'yellow' },
        { x: 1, y: 2, color: 'yellow' }
      ];
      // 设置默认行动方向 right top bottom left
      this.direction = "right";
      // 添加一个元素数组
      this.elements = [];
    }
    // 将蛇渲染到页面中
    render (map) {
      for (let i = 0, len = this.body.length; i < len; i++) {
        let piece = this.body[i];
        this.ele = document.createElement("div");
        this.ele.style.width = this.width + 'px';
        this.ele.style.height = this.height + 'px';
        this.ele.style.left = piece.x * this.width + 'px';
        this.ele.style.top = piece.y * this.height + 'px';
        this.ele.style.position = ps;
        this.ele.style.backgroundColor = piece.color;
        // 渲染
        map.appendChild(this.ele);
        this.elements.push(this.ele);
      }
    }
    // 蛇移动
    move () {
      // 蛇身位置替换
      for (var i = this.body.length - 1; i > 0; i--) {
        this.body[i].x = this.body[i - 1].x;
        this.body[i].y = this.body[i - 1].y;
      }
      // 蛇头根据方向移动
      var head = this.body[0];
      switch (this.direction) {
        case "right":
          head.x += 1;
          break;
        case "left":
          head.x -= 1;
          break;
        case "top":
          head.y -= 1;
          break
        case "bottom":
          head.y += 1;
      }
    }
    // 删除上一个蛇
    remove (map) {
      // 遍历删除所有元素
      for (var i = this.elements.length - 1; i >= 0; i--) {
        map.removeChild(this.elements[i]);
      }
      // 数组清空
      this.elements = [];
    }
  }
  window.Snake = Snake;
})(window);